<template>
  <div class="toubu">
    <!-- 头部标题 -->
    <van-nav-bar fixed>
      <template #left>
        <img class="logo" :src="imgObj" />
      </template>
      <template #right>
        <van-icon name="search" size="0.48rem" color="#fff" @click="searchFn"/>
      </template>
    </van-nav-bar>
    <van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="tanchuceng" />
    <!-- 频道铺设 -->
    <van-tabs
      v-model="active"
      animated
      sticky
      offset-top="1.226667rem"
      @click="clickfn"
    >
      <!-- 循环遍历channelList,铺设数据 -->
      <van-tab
        :title="item.name"
        v-for="item in channelList"
        :key="item.id"
        :name="item.id"
      >
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
          <!-- 加载更多 -->
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <ArticleList :arr="articlesList" @re="remove"></ArticleList>
          </van-list>
          <!-- 加载更多 -->
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
    <!-- 弹出层管理 -->
    <van-popup v-model="show" :close-on-click-overlay="false" class="edit_wrap" @closed="onPopupClosed">
  <div class="popup-container">

    <!-- 弹出层的主体区域 -->
    <div class="pop-body">
      <ChannelEdit @closePop='show=false' :userchannelList="channelList" ref="editpop" @channelId="pindao"></ChannelEdit>
    </div>
  </div>
</van-popup>
  </div>
</template>

<script>
// 把图片直接引入
import logopng from '../../assets/logo.png'
import ArticleList from './components/ArticleList.vue'
import { totime } from '@/utils/date.js'
// 引入封装好的弹出插件
import { MyNotify } from '@/utils/Notify'
// 引入时间处理插件
import {
  userChannelListAPI,
  articlesListAPI,
  articleReportsAPI,
  articleDislikeAPI
} from '@/api'
// 引入弹出层页面
import ChannelEdit from './ChannelEdit.vue'
const cacheobj = {}
export default {
  name: 'Home',
  data () {
    return {
      // 给图片一个变量接收引过来的图片
      imgObj: logopng,
      //   默认铺设的频发下标
      active: 0,
      channelId: 0,
      channelList: [],
      articlesList: [],
      //   控制加载更多的
      loading: false,
      finished: false,
      nextTime: null,
      //   下拉刷新
      isLoading: false,
      // 弹出层管理
      show: false
    }
  },
  components: {
    ArticleList,
    ChannelEdit
  },
  //   在创建的时候发送请求获取频道铺设的数据,把里面的值赋给变量channelList
  async created () {
    const res = await userChannelListAPI()
    this.channelList = res.data.data.channels
    // 调用获取文章列表的请求
    this.getArticleList()
  },
  methods: {
    totime,
    //   把获取文章列表的请求封装起来
    async getArticleList () {
      if (cacheobj[this.channelId]?.arr && this.loading === false) {
        this.articlesList = cacheobj[this.channelId].arr
        this.nextTime = cacheobj[this.channelId]?.nextTime
        this.$nextTick(() => {
          window.scrollTo(0, cacheobj[this.channelId] ? cacheobj[this.channelId].sTop : 0)
        })
      } else {
        const res2 = await articlesListAPI({
          channelId: this.channelId,
          timestamp: this.nextTime
        })
        if (res2.data.data.results.length === 0) {
          this.finished = true
          return
        }
        // 数据的预处理
        // 后台返回的数据无法直接使用
        // 提前对数据进行转换
        res2.data.data.results.forEach((obj) => {
        //   调用时间处理函数传入数组中的时间,处理完成后再塞回数组中
          obj.pubdate = this.totime(obj.pubdate)
        })
        this.articlesList = [...this.articlesList, ...res2.data.data.results]
        // 将页面数据缓存到变量中
        cacheobj[this.channelId] = {}
        cacheobj[this.channelId].arr = this.articlesList
        this.nextTime = res2.data.data.pre_timestamp
        cacheobj[this.channelId].nextTime = res2.data.data.pre_timestamp

        this.loading = false

        this.isLoading = false
      }
    },

    clickfn (channelId) {
      //   点击单击事件传入id, 是vant组件定义的默认参数, 通过修改name属性, 改成我们想要的参数,再赋值回去
      cacheobj[this.channelId].sTop = window.scrollY
      this.channelId = channelId
      console.log(cacheobj[this.channelId])
      this.articlesList = []
      // 调用获取文章列表的请求
      this.getArticleList()
    },
    onLoad () {
      if (this.articlesList.length === 0) {
        return
      }
      this.getArticleList()
    },
    // 下拉刷新
    onRefresh () {
      this.nextTime = null
      cacheobj[this.channelId].arr = null
      cacheobj[this.channelId].nextTime = null
      this.articlesList = []
      this.getArticleList()
    },
    // 删除文章并且传给后端
    // 手动删除静态页面上的文章-----------------------------------------------------------------
    async remove (item, action) {
      const index = this.articlesList.findIndex((val) => {
        return val.art_id === item.art_id
      })
      if (index !== -1) {
        this.articlesList.splice(index, 1)
      }
      //   删除静态页面上的文章传给接口----------------------------------------------------------------------------------
      if (action.name === '不感兴趣') {
        await articleDislikeAPI({
          artId: item.art_id
        })
        MyNotify({ type: 'success', message: '反馈成功' })
        // 点击一级面板中的不感兴趣,删除静态文章,并且传入数据库
      } else {
        await articleReportsAPI({
          artId: item.art_id,
          type: action.value
        })
        MyNotify({ type: 'success', message: '反馈成功' })
        // 点击二级面板中的任意,删除静态文章,并且传入数据库
      }
    },
    // 点击加号弹出
    tanchuceng () {
      this.show = true
    },
    // 关闭弹出层之后,x按钮也关闭
    onPopupClosed () {
      this.$refs.editpop.isedit = false
    },
    // 点击搜索按钮跳转路由到search页面
    searchFn () {
      this.$router.push({
        path: '/search'
      })
    },
    // 点击频道标签切换到相应的频道
    pindao (obj) {
      this.active = obj.id
      this.clickfn(obj.id)
    }
    // 跳转到文章详情页面

  },
  beforeRouteLeave (to, from, next) { // 从home去user的时候触发
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    // from是从哪里来 从/home离开的时候把 页面的滚动距离赋值给meta.top 在路由上配置的额外信息
    from.meta.top = window.scrollY
    next()
  },
  activated () {
    // 等待组件创建完成
    this.$nextTick(() => {
      if (this.$route.meta.isScoll) { // 如果里面存着滚动高度
        window.scrollTo(0, this.$route.meta.top)// 当前的滚动高度y轴是保存的高度
      }
    })
  }
}
</script>

<style scoped lang="less">
//对logo图片尺寸进行编辑
.logo {
  width: 100px;
  height: 30px;
}
// 把home上面的内容挤出来
.toubu {
  padding-top: 1.22667rem;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
